package com.z.sys.service.impl;

import com.z.common.configure.proprety.SecurityProperty;
import com.z.common.context.UserContext;
import com.z.sys.entity.SysMenu;
import com.z.sys.entity.User;
import com.z.sys.mapper.SysMenuMapper;
import com.z.sys.service.ISysMenuService;
import com.z.sys.vo.MenuVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author miko
 * @version V1.0
 * @date 2021/12/29 14:43
 * @Description:
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;
    /**
     * 超级管理员配置
     */
    @Resource
    private SecurityProperty securityProperty;
    /**
     * Describe: 获取用户菜单
     * Param: username
     * Return: Result
     */
    @Override
    public List<MenuVo> getCurrentUserMenu() {
        User user = UserContext.currentUser();
        String username = user.getUsername();
        String name = !(securityProperty.isSuperAuthOpen() && username.equals(securityProperty.getSuperAdmin())) ? username : "";
        return toUserMenu(sysMenuMapper.selectMenuByUsername(name), "0");
    }

    /**
     * Describe: 递归获取菜单tree
     * Param: sysMenus
     * Return: 操作结果
     */
    @Override
    public List<MenuVo> toUserMenu(List<SysMenu> sysMenus, String parentId) {
        List<MenuVo> list = new ArrayList<>();
        for (SysMenu menu : sysMenus) {
            if (parentId.equals(menu.getParentId())) {
                MenuVo menuVo = new MenuVo(menu.getName(), menu.getOpenType(), menu.getIcon(), menu.getHref());
                menuVo.setChild(toUserMenu(sysMenus, menu.getId()));
                list.add(menuVo);
            }
        }
        return list;
    }

    @Override
    public List<SysMenu> selectPageMenuForCurrentUser() {
        Long userId = UserContext.currentUser().getId();
        List<SysMenu> menuList = menuList = sysMenuMapper.selectPorPageMenuByUserId(userId + "");
        if(menuList == null || menuList.size() < 1){
            menuList = sysMenuMapper.selectPageMenuByUserId(userId + "");
        }
        return menuList;
    }

}
